<script setup>
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { ref, computed } from 'vue'
	import { useUserStore } from '@/store/user'
	import { addShopCar, delShopCar, clearShopCar, getCarSpecial, getDeviceGoods, computeShopCar } from '@/api/shop'
	
	const user = useUserStore()
	const loading = ref(false)
	const config = getApp().globalData.config
	const goodsOptions = ref([{text: '删除', style: {backgroundColor: '#FF1313'}}])
	const selectAll = ref([])
	const foodList = computed(() => {
		return user.shopCar.filter(item => item.type === 'INGREDIENT' && item.info && item.info.status > 0)
	})
	const specialList = computed(() => {
		return user.shopCar.filter(item => item.type === 'DISHES' && item.info && item.info.status > 0)
	})
	const specialDiyList = computed(() => {
		return user.shopCar.filter(item => item.type === 'DISHES_DIY' && item.info && item.info.status > 0)
	})
	const deviceList = computed(() => {
		return user.shopCar.filter(item => item.type === 'DEVICE' && item.info && item.info.status > 0)
	})
	const loseList = computed(() => {
		return user.shopCar.filter(item => !item.info || item.info && item.info.status === 0 )
	})
	const selectFoodList = ref([])
	const selectSpecialList = ref([])
	const selectSpecialDiyList = ref([])
	const selectDeviceList = ref([])
	const totalPrice = ref(0)
	const specialPopup = ref(null)
	const curSpecial = ref({name: '', list: []})
	const devicePopup = ref(null)
	const curDevice = ref({name: '', list: []})
	
	function openPage(url) {
		if(url) uni.navigateTo({url})
		else uni.showToast({icon: 'none',title: '敬请期待！'})
	}
	function clearFood() {
		uni.showModal({
			title: '提示',
			content: '确定清空普通商品吗?',
			cancelText: '取消',
			confirmText: '确定',
			success: res => {
				if (res.confirm) {
					loading.value = true
					clearShopCar('INGREDIENT').then(res => {
						uni.showToast({icon: 'success', title: '清空成功'})
						user.shopCarAction(true, true).then(() => {
							selectChange()
						})
						loading.value = false
					}).catch(() => loading.value = false)
				}
			}
		})
	}
	function clearSpecial() {
		uni.showModal({
			title: '提示',
			content: '确定清空特色菜品吗?',
			cancelText: '取消',
			confirmText: '确定',
			success: res => {
				if (res.confirm) {
					loading.value = true
					clearShopCar('DISHES').then(res => {
						uni.showToast({icon: 'success', title: '清空成功'})
						user.shopCarAction(true, true).then(() => {
							selectChange()
						})
						loading.value = false
					}).catch(() => loading.value = false)
				}
			}
		})
	}
	function clearSpecialDiy() {
		uni.showModal({
			title: '提示',
			content: '确定清空个性菜品吗?',
			cancelText: '取消',
			confirmText: '确定',
			success: res => {
				if (res.confirm) {
					loading.value = true
					clearShopCar('DISHES_DIY').then(res => {
						uni.showToast({icon: 'success', title: '清空成功'})
						user.shopCarAction(true, true).then(() => {
							selectChange()
						})
						loading.value = false
					}).catch(() => loading.value = false)
				}
			}
		})
	}
	function clearDevice() {
		uni.showModal({
			title: '提示',
			content: '确定清空智慧餐车吗?',
			cancelText: '取消',
			confirmText: '确定',
			success: res => {
				if (res.confirm) {
					loading.value = true
					clearShopCar('DEVICE').then(res => {
						uni.showToast({icon: 'success', title: '清空成功'})
						user.shopCarAction(true, true).then(() => {
							selectChange()
						})
						loading.value = false
					}).catch(() => loading.value = false)
				}
			}
		})
	}
	function clearLose() {
		uni.showModal({
			title: '提示',
			content: '确定清空失效商品吗?',
			cancelText: '取消',
			confirmText: '确定',
			success: res => {
				if (res.confirm) {
					loading.value = true
					clearShopCar('UNKNOWN').then(res => {
						uni.showToast({icon: 'success', title: '清空成功'})
						user.shopCarAction(true, true)
						loading.value = false
					}).catch(() => loading.value = false)
				}
			}
		})
	}
	function delCarGoods(e) {
		let cartId = e.name
		let item = user.shopCar.find(item => item.cartId === cartId)
		if(item) {
			delGoods(item)
		} else {
			uni.showToast({icon: 'none', title: '找不到商品'})
		}
	}
	function changelGoods(e, item) {
		if(e.num === 0) {
			delGoods(item, 1)
		} else {
			loading.value = true
			addShopCar({cartId: item.cartId, goodsId: item.goodsId, type: item.type, num: e.num}).then(res => {
				loading.value = false
				if(item.type === 'DEVICE'){
					user.shopCarAction(true, true).then(() => {
						selectChange()
					})
				} else selectChange()
				
			}).catch(() => loading.value = false)
		}
	}
	function delGoods(item, num) {
		uni.showModal({
			title: '提示',
			content: `确定删除“${item.info && item.info.goodsName || '未知'}”商品吗?`,
			cancelText: '取消',
			confirmText: '确定',
			success: res => {
				if (res.confirm) {
					loading.value = true
					delShopCar([item.cartId]).then(res => {
						loading.value = false
						uni.showToast({icon: 'success', title: '删除成功'})
						user.shopCarAction(true, true).then(() => {
							selectChange()
						})
					}).catch(() => loading.value = false)
				} else {
					if(num) item.num = 1
				}
			}
		})
	}
	function viewSpecial(item) {
		loading.value = true
		getCarSpecial(item.cartId).then(res => {
			loading.value = false
			let result = res.result || []
			curSpecial.value.name = item.info.goodsName
			curSpecial.value.list = result
			specialPopup.value.open()
		}).catch(() => loading.value = false)
	}
	function viewDevice(item) {
		loading.value = true
		getDeviceGoods(item.goodsId, user.addressIds[2]).then(res => {
			loading.value = false
			let result = res.result || {}
			let data = result.devices || []
			curDevice.value.name = item.info.goodsName
			curDevice.value.list = data
			devicePopup.value.open()
		}).catch(() => loading.value = false)
	}
	function selectChange(e) {
		selectFoodList.value.forEach((id, index) => {
			let food = foodList.value.find(item => item.cartId === id)
			if(!food) selectFoodList.value.splice(index, 1)
		})
		selectSpecialList.value.forEach((id, index) => {
			let food = specialList.value.find(item => item.cartId === id)
			if(!food) selectSpecialList.value.splice(index, 1)
		})
		selectSpecialDiyList.value.forEach((id, index) => {
			let food = specialDiyList.value.find(item => item.cartId === id)
			if(!food) selectSpecialDiyList.value.splice(index, 1)
		})
		selectDeviceList.value.forEach((id, index) => {
			let food = deviceList.value.find(item => item.cartId === id)
			if(!food) selectDeviceList.value.splice(index, 1)
		})
		let selectTotal = selectFoodList.value.length + selectSpecialList.value.length + selectSpecialDiyList.value.length + selectDeviceList.value.length
		let curTotal = foodList.value.filter(item => item.info.status < 2).length + specialList.value.filter(item => item.info.status < 2).length + 
			specialDiyList.value.filter(item => item.info.status < 2).length + deviceList.value.filter(item => item.info.status < 2).length
		if(curTotal > 0) {
			selectAll.value = curTotal === selectTotal? ['total'] : []
		}
		computePrice()
	}
	function selectAllChange(e) {
		if(e.includes('total')) {
			selectFoodList.value = foodList.value.reduce((arr, item) => {
				if(item.info.status < 2) arr.push(item.cartId)
				return arr
			}, [])
			selectSpecialList.value = specialList.value.reduce((arr, item) => {
				if(item.info.status < 2) arr.push(item.cartId)
				return arr
			}, [])
			selectSpecialDiyList.value = specialDiyList.value.reduce((arr, item) => {
				if(item.info.status < 2) arr.push(item.cartId)
				return arr
			}, [])
			selectDeviceList.value = deviceList.value.reduce((arr, item) => {
				if(item.info.status < 2) arr.push(item.cartId)
				return arr
			}, [])
		} else {
			selectFoodList.value = []
			selectSpecialList.value = []
			selectSpecialDiyList.value = []
			selectDeviceList.value = []
		}
		selectChange()
	}
	function computePrice() {
		let goodsList = dealData()
		if(!goodsList.length) {
			totalPrice.value = 0
			return
		}
		let list = goodsList.map(item => {
			return {
				cartId: item.cartId,
				goodsId: item.id,
				num: item.number,
				type: item.type
			}
		})
		loading.value = true
		computeShopCar({
			areaId: user.addressIds[2],
			type: 'COMBINATION',
			list
		}).then(res => {
			loading.value = false
			let result = res.result || {}
			totalPrice.value = result.totalOriginal
		}).catch(() => loading.value = false)
	}
	function dealData() {
		let goodsList = []
		selectFoodList.value.forEach(id => {
			let food = foodList.value.find(item => item.cartId === id)
			if(food) goodsList.push({
				cartId: food.cartId,
				id: food.goodsId,
				name: food.info.goodsName,
				furl: food.info.img && food.info.img.furl || '',
				price: food.info.price,
				specs: food.info.specs,
				number: food.num,
				type: 'INGREDIENT'
			})
		})
		selectSpecialList.value.forEach(id => {
			let food = specialList.value.find(item => item.cartId === id)
			if(food) {
				let children = food
				goodsList.push({
					cartId: food.cartId,
					id: food.goodsId,
					name: food.info.goodsName,
					furl: food.info.img && food.info.img.furl || '',
					price: food.info.price,
					number: food.num,
					type: 'DISHES'
				})
			}
		})
		selectSpecialDiyList.value.forEach(id => {
			let food = specialDiyList.value.find(item => item.cartId === id)
			if(food) goodsList.push({
				cartId: food.cartId,
				id: food.goodsId,
				name: food.info.goodsName,
				furl: food.info.img && food.info.img.furl || '',
				price: food.info.price,
				number: food.num,
				type: 'DISHES_DIY'
			})
		})
		selectDeviceList.value.forEach(id => {
			let food = deviceList.value.find(item => item.cartId === id)
			if(food) goodsList.push({
				cartId: food.cartId,
				id: food.goodsId,
				name: food.info.goodsName,
				furl: food.info.img && food.info.img.furl || '',
				price: food.info.price,
				number: food.num,
				type: 'DEVICE'
			})
		})
		return goodsList
	}
	function goBuy() {
		if(loading.value) return
		let goodsList = dealData()
		if(!goodsList.length) {
			uni.showToast({icon: 'none', title: '请选择商品'})
			return
		}
		loading.value = true
		let data = {
			total: totalPrice.value,
			list: goodsList,
			type: 'COMBINATION'
		}
		uni.navigateTo({
			url: '/pages/shop/orderConfirm',
			success: res => {
				res.eventChannel.emit('orderConfirm', data)
			}
		})
		loading.value = false
	}
	
	onShow(() => {
		if(user.userId) {
			user.shopCarAction(true, true)
			selectChange()
		}
	})
	onLoad(() => {
		
	})
</script>

<template>
	<view class="app-container">
		<view class="app-content" v-if="user.userId">
			<template v-if="foodList.length || specialList.length || specialDiyList.length || deviceList.length">
				<view class="car-box" v-if="foodList.length">
					<view class="car-head">
						<text class="car-title">普通商品</text>
						<text class="car-edit" @click="clearFood">清空</text>
					</view>
					<uv-checkbox-group v-model="selectFoodList" placement="column" shape="circle" size="32" iconSize="32" activeColor="#FA3F00"
						@change="selectChange">
						<uv-swipe-action>
							<view class="car-list" v-for="(item, index) in foodList" :key="item.cartId">
								<uv-swipe-action-item :name="item.cartId" :options="goodsOptions" @click="delCarGoods">
									<uv-checkbox :custom-style="{padding: '0 24rpx'}" :name="item.cartId" :disabled="item.info.status > 1">
										<goods v-model="item.num" :img="item.info.img && item.info.img.furl" :name="item.info.goodsName" :price="item.info.price"
											:specs="item.info.specs" :min="item.info.minNum" :max="item.info.maxNum" :disabled="item.info.status > 1"
											@change="changelGoods($event, item)"></goods>
									</uv-checkbox>
								</uv-swipe-action-item>
								<view class="car-gap" v-if="index < foodList.length - 1"></view>
							</view>
						</uv-swipe-action>
					</uv-checkbox-group>
				</view>
				<view class="car-box mg-top" v-if="specialList.length">
					<view class="car-head">
						<text class="car-title">特色菜品</text>
						<text class="car-edit" @click="clearSpecial">清空</text>
					</view>
					<uv-checkbox-group v-model="selectSpecialList" placement="column" shape="circle" size="32" iconSize="32" activeColor="#FA3F00"
						@change="selectChange">
						<uv-swipe-action>
							<view class="car-list" v-for="(item, index) in specialList" :key="item.cartId">
								<uv-swipe-action-item :name="item.cartId" :options="goodsOptions" @click="delCarGoods">
									<uv-checkbox :custom-style="{padding: '0 24rpx'}" :name="item.cartId" :disabled="item.info.status > 1">
										<goods v-model="item.num" :img="item.info.img && item.info.img.furl" :name="item.info.goodsName" :price="item.info.price"
											:specs="item.info.specs" :disabled="item.info.status > 1" @change="changelGoods($event, item)">
											<view class="special-detail" @click.stop="viewSpecial(item)" v-if="item.info.status < 2">菜单详情</view>
										</goods>
									</uv-checkbox>
								</uv-swipe-action-item>
								<view class="car-gap" v-if="index < specialList.length - 1"></view>
							</view>
						</uv-swipe-action>
					</uv-checkbox-group>
				</view>
				<view class="car-box mg-top" v-if="specialDiyList.length">
					<view class="car-head">
						<text class="car-title">个性菜品</text>
						<text class="car-edit" @click="clearSpecialDiy">清空</text>
					</view>
					<uv-checkbox-group v-model="selectSpecialDiyList" placement="column" shape="circle" size="32" iconSize="32" activeColor="#FA3F00"
						@change="selectChange">
						<uv-swipe-action>
							<view class="car-list" v-for="(item, index) in specialDiyList" :key="item.cartId">
								<uv-swipe-action-item :name="item.cartId" :options="goodsOptions" @click="delCarGoods">
									<uv-checkbox :custom-style="{padding: '0 24rpx'}" :name="item.cartId" :disabled="item.info.status > 1">
										<goods v-model="item.num" :img="item.info.img && item.info.img.furl" :name="item.info.goodsName" :price="item.info.price"
											:specs="item.info.specs" :disabled="item.info.status > 1" @change="changelGoods($event, item)"></goods>
									</uv-checkbox>
								</uv-swipe-action-item>
								<view class="car-gap" v-if="index < specialDiyList.length - 1"></view>
							</view>
						</uv-swipe-action>
					</uv-checkbox-group>
				</view>
				<view class="car-box mg-top" v-if="deviceList.length">
					<view class="car-head">
						<text class="car-title">智慧餐车</text>
						<text class="car-edit" @click="clearDevice">清空</text>
					</view>
					<uv-checkbox-group v-model="selectDeviceList" placement="column" shape="circle" size="32" iconSize="32" activeColor="#FA3F00"
						@change="selectChange">
						<uv-swipe-action>
							<view class="car-list" v-for="(item, index) in deviceList" :key="item.cartId">
								<uv-swipe-action-item :name="item.cartId" :options="goodsOptions" @click="delCarGoods">
									<uv-checkbox :custom-style="{padding: '0 24rpx'}" :name="item.cartId" :disabled="item.info.status > 1">
										<goods v-model="item.num" :img="item.info.img && item.info.img.furl" :name="item.info.goodsName" :price="item.info.price"
											:specs="item.info.specs" :max="3" :disabled="item.info.status > 1" @change="changelGoods($event, item)">
											<view class="special-detail" @click.stop="viewDevice(item)" v-if="item.info.status < 2">餐车详情</view>
										</goods>
									</uv-checkbox>
								</uv-swipe-action-item>
								<view class="car-gap" v-if="index < deviceList.length - 1"></view>
							</view>
						</uv-swipe-action>
					</uv-checkbox-group>
				</view>
			</template>
			<view class="car-empty" v-else>
				<empty src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-15/1739584283006_shop-car.png" 
					:srcSize="338" text="购物车为空" textColor="#CDCDCD">
					<view class="empty-btn">
						<uv-button shape="circle" text="去选购" :custom-style="{background: '#ffffff', border: '2rpx solid #FF1313', color: '#FF1313'}"
							@click="openPage('/pages/shop/foodSelect')"></uv-button>
					</view>
				</empty>
			</view>
			<view class="car-box mg-top" v-if="loseList.length">
				<view class="car-head">
					<text class="car-title">失效商品</text>
					<text class="car-edit" @click="clearLose">清空</text>
				</view>
				<uv-checkbox-group placement="column" shape="circle" size="32" iconSize="32" activeColor="#FA3F00" disabled>
					<uv-swipe-action>
						<view class="car-list" v-for="(item, index) in loseList" :key="item.cartId">
							<uv-swipe-action-item :name="item.cartId" :options="goodsOptions" @click="delCarGoods">
								<uv-checkbox :custom-style="{padding: '0 24rpx'}" :name="item.cartId" checked>
									<goods v-model="item.num" :img="item.info && item.info.img && item.info.img.furl" :name="item.info && item.info.goodsName" :price="item.info && item.info.price" :specs="item.info && item.info.specs" @change="changelGoods($event, item)" 
										mode="invalid"></goods>
								</uv-checkbox>
							</uv-swipe-action-item>
							<view class="car-gap" v-if="index < loseList.length - 1"></view>
						</view>
					</uv-swipe-action>
				</uv-checkbox-group>
			</view>
			<view class="app-bottom">
				<view class="bottom-left">
					<uv-checkbox-group v-model="selectAll" shape="circle" size="32" iconSize="32" labelSize="28" activeColor="#FA3F00" @change="selectAllChange">
						<uv-checkbox label="全选" name="total"></uv-checkbox>
					</uv-checkbox-group>
					<view class="bottom-total">总计：<text class="text-price">{{totalPrice? totalPrice.toFixed(2) : 0.00}}</text></view>
				</view>
				<uv-button color="linear-gradient( 102deg, #FA3F00 0%, #FF7445 100%)" :custom-style="{width: '200rpx'}" shape="circle" text="去下单"
					:disabled="loading" @click="goBuy"></uv-button>
			</view>
		</view>
		<view class="app-login" v-else>
			<empty src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-15/1739584283006_shop-car.png" :srcSize="338" text="点击登录查看购物车" textColor="#CDCDCD">
				<view class="login-btn">
					<uv-button color="#FF3E49" shape="circle" size="large" text="登 录" @click="openPage('/pages/login')"></uv-button>
				</view>
			</empty>
		</view>
		
		<uv-popup ref="specialPopup" closeable mode="bottom" round="32" :safeAreaInsetBottom="false">
			<view class="popup-box">
				<view class="popup-title">{{curSpecial.name}}详情</view>
				<view class="popup-content">
					<scroll-view scroll-y="true" class="popup-content">
						<view class="goods-list" v-if="curSpecial.list && curSpecial.list.length">
							<view class="goods-box" v-for="item in curSpecial.list" :key="item.cartId">
								<goods v-model="item.num" :img="item.info.img && item.info.img.furl" :name="item.info.goodsName" 
									:price="item.info.price" mode="viewD" v-if="item.info"></goods>
								<goods v-model="item.num" mode="invalidD" v-else></goods>
							</view>
						</view>
						<empty text="没有找到菜单详情" v-else></empty>
					</scroll-view>
				</view>
			</view>
		</uv-popup>
		<uv-popup ref="devicePopup" closeable mode="bottom" round="32" :safeAreaInsetBottom="false">
			<view class="popup-box">
				<view class="popup-title">{{curDevice.name}}详情</view>
				<view class="popup-content">
					<scroll-view scroll-y="true" class="popup-content">
						<view class="goods-list" v-if="curDevice.list && curDevice.list.length">
							<view class="goods-box goods-padding" v-for="item in curDevice.list" :key="item.deviceId">
								<goods v-model="item.quantity" :img="item.image && item.image.furl" :name="item.deviceName" :des="item.detail" mode="viewM"></goods>
							</view>
						</view>
						<empty text="没有找到该设备下的商品" v-else></empty>
					</scroll-view>
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		.app-content{
			padding: 2rpx 0 140rpx;
			.car-head{
				padding: 0 24rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-weight: 600;
				.car-title{
					font-size: var(--theme-lg);
					line-height: var(--theme-lg-line);
				}
				.car-edit{
					color: #FF1313;
				}
			}
			.car-list{
				padding-top: 24rpx;
				.car-gap{
					margin: 24rpx 24rpx 0;
					height: 2rpx;
					background-color: #F4F4F4;
				}
				.special-detail{
					flex: 1;
					color: #FA3F00;
					text-align: center;
					background-color: rgba(250,63,0,0.1);
					border: 4rpx solid rgba(250,63,0,0.1);
					border-radius: 16rpx;
					font-size: var(--theme-sm);
					line-height: var(--theme-sm-line);
				}
			}
			.car-box{
				padding: 24rpx 0;
				background-color: #FFFFFF;
			}
			.mg-top{
				margin-top: 16rpx;
			}
			.car-empty{
				height: calc(100vh - 142rpx);
				background-color: #FFFFFF;
				.empty-btn{
					margin-top: 32rpx;
					width: 200rpx;
					font-weight: 600;
				}
			}
		}
		.app-bottom{
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 100;
			height: 112rpx;
			background: #ffffff;
			padding: 16rpx 24rpx;
			display: flex;
			align-items: center;
			gap: 32rpx;
			border-top: 2rpx solid #D7DBE1;
			border-bottom: 2rpx solid #D7DBE1;
			.bottom-left{
				width: calc(100% - 232rpx);
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-weight: 600;
				.text-price{
					color: #FF0D0D;
					font-size: var(--theme-lg);
					line-height: var(--theme-lg-line);
					&::before{
						content: "¥";
						font-size: 60%;
					}
				}
			}
		}
		.app-login{
			height: 80vh;
			.login-btn{
				width: 600rpx;
				padding-top: 92rpx;
			}
		}
		.popup-box{
			width: 100%;
			min-height: 600rpx;
			background: linear-gradient( 180deg, #F9EBE7 0%, #FFFFFF 12%);
			.popup-title{
				padding: 24rpx 0 16rpx;
				font-weight: 600;
				font-size: var(--theme-lg);
				line-height: var(--theme-lg-line);
				text-align: center;
			}
			.popup-content{
				height: 760rpx;
				.goods-list{
					padding: 24rpx;
					display: flex;
					flex-direction: column;
					gap: 16rpx;
					.goods-box{
						background-color: #FEF3F1;
						padding-right: 8rpx;
						border-radius: 16rpx;
					}
					.goods-padding{
						padding: 16rpx;
					}
				}
			}
		}
	}
</style>